package com.qxf.service;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jfree.util.Log;

import com.qxf.util.db.SQLProcessor;
import com.qxf.util.db.SQLUtil;

public class RedirectService extends HttpServlet {

	private static final long serialVersionUID = 8440734830131439386L;
	
	static Logger log = Logger.getLogger(RedirectService.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String adpId = req.getParameter("f");
		String activityUrl = req.getParameter("a");
		
		if(null==adpId || adpId.trim().length()==0
				|| null==activityUrl || activityUrl.trim().length()==0) {
			resp.sendRedirect("index.jsp");
			log.warn("***广告位活动链接异常！***");
			return;
		}
		
		try {
			if(addClickCount(adpId)) {
				resp.sendRedirect(activityUrl);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private synchronized boolean addClickCount(String adpId) throws SQLException {
		SQLProcessor sp = null;
		String sql = "";
		int flag = -1;
		
		try {
			sql = "update tb_ad set ad_clickcount=ad_clickcount+1 where ad_id=" + SQLUtil.toSqlInt(adpId);
			Log.info("addClickCount():" + sql);
			sp = new SQLProcessor();
			flag = sp.executeUpdate(sql);
			if(flag != -1) {
				return true;
			}
		} catch (SQLException e) {
			sp.rollback();
			e.printStackTrace();
		} finally {
			sp.close();
		}
		return false;
	}

}
